package org.zch.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zch.dao.MessageDAO;
import org.zch.entity.dto.MessageDTO;
import org.zch.entity.po.MessagePO;
import org.zch.entity.vo.UserInfoVO;
import org.zch.service.MessageService;
import org.zch.service.UserService;

import java.util.Date;
import java.util.List;

/**
 * 消息表(Message)表服务实现类
 *
 * @author 刘新
 * @since 2024-01-12 14:09:31
 */
@Service("messageService")
public class MessageServiceImpl extends ServiceImpl<MessageDAO, MessagePO> implements MessageService {

    @Autowired
    private MessageDAO messageDAO;
    @Autowired
    private UserService userService;

    /**
     * 消息列表
     *
     * @param dto 查询条件
     * @return 分页列表
     */
    @Override
    public IPage<MessagePO> getMessage(MessageDTO dto) {
        //全部设为已读
        this.messageDAO.updateAllRead();
        return this.messageDAO.getMessage(dto);
    }

    /**
     * 发送消息
     *
     * @param msgPO 消息体
     * @return 发送成功条数
     */
    @Override
    public Integer sendMsg(MessagePO msgPO) {
        msgPO.setGetRead(false);
        msgPO.setCreateTime(new Date());
        return messageDAO.insert(msgPO);
    }

    /**
     * 给指定用户发送消息
     *
     * @param msgPO sendUserCode：消息发送人code
     *              toUserCode： 消息接收人code
     *              msgContent: 消息内容
     * @return
     */
    @Override
    public Integer sendMsgToUser(MessagePO msgPO) {
        UserInfoVO sendUser = userService.getByCode(msgPO.getSendUserCode());
        UserInfoVO toUser = userService.getByCode(msgPO.getToUserCode());
        msgPO.setSendUserId(sendUser.getId());
        msgPO.setToUserId(toUser.getId());
        msgPO.setRelateId(sendUser.getId());
        msgPO.setSource(3);
        msgPO.setGetRead(false);
        msgPO.setCreateTime(new Date());
        return messageDAO.insert(msgPO);
    }

    /**
     * 根据code，查询是否有未读消息
     *
     * @param code
     * @return
     */
    @Override
    public Integer haveUnreadMsg(String code) {
        Integer have = 0;
        MessageDTO dto = new MessageDTO();
        dto.setUserCode(code);
        dto.setRead(0);
        IPage<MessagePO> iPage = messageDAO.getMessage(dto);
        if (ArrayUtil.isAllNotEmpty(iPage)){
            List<MessagePO> records = iPage.getRecords();
            if (ArrayUtil.isAllNotEmpty(records)){
                have = 1;
            }
        }
        return have;
    }

    /**
     * 批量已读消息
     *
     * @param list 主键ids
     * @return
     */
    @Override
    public Integer updateRead(List<Integer> list) {
        return messageDAO.updateRead(list);
    }

    /**
     * 将全部消息设为已读*/
    @Override
    public Integer updateAllRead() {
        return messageDAO.updateAllRead();
    }
}

